package com.cmict.data.form.api.util;


import cn.hutool.core.util.ObjectUtil;
import com.cmict.data.form.api.entity.dataobject.SysFormDO;
import com.cmict.data.form.api.service.SysCurrencyService;
import com.cmict.data.form.api.service.SysFormService;
import com.cmict.data.form.controller.admin.SysCurrencyController;
import com.cmict.data.framework.common.pojo.CommonResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cmict.data.infra.api.rdb.RdbApi;
import com.cmict.data.system.api.dept.DeptApi;
import com.cmict.data.system.api.dept.PostApi;
import com.cmict.data.system.api.dept.dto.DeptRespDTO;
import com.cmict.data.system.api.dept.dto.PostDTO;
import com.cmict.data.system.api.dict.DictDataApi;
import com.cmict.data.system.api.dict.dto.DictDataDTO;
import com.cmict.data.system.api.user.AdminUserApi;
import com.cmict.data.system.api.user.dto.AdminUserRespDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
import java.util.stream.Collectors;

import static com.cmict.data.framework.common.pojo.CommonResult.success;

/**
 * @description: 导入字段类型工具类
 * @author: qiaoyu
 * @create: 2022-07-08 22:57
 **/
@Component
public class AssemblyTypeUtil {
    private static final Logger logger = LoggerFactory.getLogger(SysCurrencyController.class);

    @Autowired
    private SysFormService sysFormService;
    private static SysFormService realsysFormService;

    @Autowired
    private SysCurrencyService sysCurrencyService;
    private static SysCurrencyService realsysCurrencyService;

    @Autowired
    private DictDataApi dictDataService;
    private static DictDataApi realdictDataService;

    @Autowired
    private DeptApi deptService;
    private static DeptApi realdeptService;

    @Autowired
    private AdminUserApi adminUserService;
    private static AdminUserApi realadminUserService;

    @Autowired
    private PostApi postService;
    private static PostApi realpostService;

    @Autowired
    private RdbApi rdbApiService;
    private static RdbApi realrdbapiService;


    @PostConstruct
    public void init() {
        realsysFormService = sysFormService;
        realsysCurrencyService = sysCurrencyService;
        realdictDataService = dictDataService;
        realdeptService = deptService;
        realadminUserService = adminUserService;
        realpostService = postService;
        realrdbapiService = rdbApiService;
    }
    /**
     * 联动、关联、级联组件用
     */
    public static CommonResult selectReplaceValue(String tableName,String columnName, String value) {
        Map<String,Object> map = new HashMap<>();
        map.put(columnName,value);
        SysFormDO sysForm = realsysFormService.selectOneByTableName(tableName);
        if(ObjectUtil.isNotEmpty(sysForm)){
            JSONObject personData = JSON.parseObject(sysForm.getFormJsonUser());
            JSONArray fields = personData.getJSONArray("fields");
            if(ObjectUtil.isNotEmpty(fields)){
                for (int i = 0; i <fields.size() ; i++) {
                    //测试一下关联和联动、级联是不是以下通用的取值位置****************
                    JSONObject field = fields.getJSONObject(i);
                    JSONObject config = fields.getJSONObject(i).getJSONObject("__config__");
                    String tagIcon = config.getString("tagIcon");
                    String datatype = fields.getJSONObject(i).getString("dataType");
                    String Model = fields.getJSONObject(i).getString("__vModel__");
                    map = map(field,tagIcon,datatype,Model,map,"static",null);
                }
            }
        }
        return success(map.get(columnName));
    }
    /**
     *映射数据替换通用方法
     */
    public static CommonResult<List<Map<String, Object>>> associatedDataMapping(Long formId, List<Map<String,Object>> dataMapList,String portal) {
        SysFormDO sysFormDO = realsysFormService.selectById(formId);
        return associatedDataMapping(sysFormDO, dataMapList, portal);
    }

    public static CommonResult<List<Map<String, Object>>> associatedDataMapping(String tableName, List<Map<String,Object>> dataMapList,String portal) {
        SysFormDO sysForm = realsysFormService.selectOneByTableName(tableName);
        return  associatedDataMapping(sysForm, dataMapList, portal);
    }

    private static CommonResult<List<Map<String, Object>>> associatedDataMapping(SysFormDO sysForm, List<Map<String,Object>> dataMapList,String portal) {
        if(ObjectUtil.isEmpty(sysForm)){
            return success(dataMapList);
        }
        List<Map<String, Object>> returnMapList = dataMapList.parallelStream().map(item -> {
            JSONObject personData = JSON.parseObject(sysForm.getFormJsonUser());
            JSONArray fields = personData.getJSONArray("fields");
            if (ObjectUtil.isNotEmpty(fields)) {
                for (int j = 0; j < fields.size(); j++) {
                    JSONObject field = fields.getJSONObject(j);
                    JSONObject config = fields.getJSONObject(j).getJSONObject("__config__");
                    String tagIcon = config.getString("tagIcon");
                    String datatype = field.getString("dataType");
                    //多选
                    String multiple = field.getString("multiple");
                    //增加是否多选获取多选
                    String Model = field.getString("__vModel__");
                    if(ObjectUtil.isNotEmpty(Model)){
                        item = map(field,tagIcon,datatype,Model,item,portal,multiple);
                    }
                }
                return item;
            } else {
                JSONObject config = personData.getJSONObject("__config__");
                JSONArray childrenList = config.getJSONArray("children");
                for (int j = 0; j < childrenList.size(); j++) {
                    JSONObject object = (JSONObject) childrenList.get(j);
                    JSONObject configchild = object.getJSONObject("__config__");
                    JSONArray childfields = configchild.getJSONArray("children");
                    for (int k = 0; k < childfields.size(); k++) {
                        JSONObject children = (JSONObject) childfields.get(k);
                        JSONObject configchildtwo = children.getJSONObject("__config__");
                        String tagIcon = configchildtwo.getString("tagIcon");
                        String datatype = children.getString("dataType");
                        //多选
                        String multiple = children.getString("multiple");
                        String Model = children.getString("__vModel__");
                        if(ObjectUtil.isNotEmpty(Model)){
                            item = map(children,tagIcon,datatype,Model,item,portal,multiple);
                        }
                    }
                }
                return item;
            }
        }).collect(Collectors.toList());
        return success(returnMapList);
    }


    static Map<String,Object> map(JSONObject field, String tagIcon, String datatype, String Model, Map<String,Object> map,String portal,String multiple) {
        if("select".equals(tagIcon)) {
            //表单静态数据前端解析，流程测判断portal使用
            if (StringUtils.isNoneBlank(portal)) {
                //静态数据
                if ("static".equals(datatype)) {
                    JSONArray options = field.getJSONArray("options");
                    String returncalue = "";
                    if (ObjectUtil.isNotEmpty(multiple) || "checkbox".equals(tagIcon)) {
                        String valu = String.valueOf(map.get(Model));
                        List<String> values = new ArrayList<>();
                        if (ObjectUtil.isNotEmpty(valu)) {
                            values = Arrays.asList(valu.split(","));
                        }
                        for (int i = 0; i < values.size(); i++) {
                            for (int k = 0; k < options.size(); k++) {
                                if (options.getJSONObject(k).getString("value").equals(values.get(i))) {
                                    returncalue = returncalue + options.getJSONObject(k).getString("label") + ",";
                                }
                            }
                        }
                    } else {
                        for (int k = 0; k < options.size(); k++) {
                            if (options.getJSONObject(k).getString("value").equals(String.valueOf(map.get(Model)))) {
                                returncalue = options.getJSONObject(k).getString("label");
                            }
                        }
                    }
                    if (ObjectUtil.isNotEmpty(returncalue)) {
                        if (returncalue.substring(returncalue.length() - 1).equals(",")) {
                            returncalue = returncalue.substring(0, returncalue.length() - 1);
                        }
                    }
                    if("null".equals(returncalue)){
                        returncalue = "";
                    }
                    map.put(Model, returncalue);
                }
            }
            //数据字典
            if ("dictionary".equals(datatype)) {
                String dictType = field.getString("dictName");
                List<DictDataDTO> list = realdictDataService.getListByDictType(dictType).getCheckedData();
                String valu = String.valueOf(map.get(Model));
                List<String> values = new ArrayList<>();
                if (ObjectUtil.isNotEmpty(valu)) {
                    values = Arrays.asList(valu.split(","));
                }
                String returncalue = "";
                for (int i = 0; i < values.size(); i++) {
                    if (ObjectUtil.isNotEmpty(multiple) || "checkbox".equals(tagIcon)) {
                        for (int k = 0; k < list.size(); k++) {
                            if (String.valueOf(list.get(k).getValue()).equals(values.get(i))) {
                                returncalue = returncalue + list.get(k).getLabel() + ",";
                            }
                        }
                    } else {
                        for (int k = 0; k < list.size(); k++) {
                            if (String.valueOf(list.get(k).getValue()).equals(String.valueOf(map.get(Model)))) {
                                returncalue = list.get(k).getLabel();
                            }
                        }
                    }
                }
                if (ObjectUtil.isNotEmpty(returncalue)) {
                    if (returncalue.substring(returncalue.length() - 1).equals(",")) {
                        returncalue = returncalue.substring(0, returncalue.length() - 1);
                    }
                }
                if("null".equals(returncalue)){
                    returncalue = "";
                }
                map.put(Model, returncalue);
            }
            //数据源
            if ("datasource".equals(datatype)) {
                Long disTableName = field.getLong("tableName");
                String disFieldName = field.getString("fieldName");
                String dislinkName = field.getString("saveFieldName");
            /*dislinkName = "username";
            disFieldName = "nickname";
            sourceId = Long.parseLong(String.valueOf(204));*/
                //数据来源为源管理
                if (ObjectUtil.isNotEmpty(disTableName)) {
                    //数据源接口获取数据
                    CommonResult json = realrdbapiService.sourceTestList(disTableName);
                    Map<Object, Object> mappp = (Map<Object, Object>) json.getData();
                    List<Map<Object, Object>> mapList = (List<Map<Object, Object>>) mappp.get("rowMaps");
                    String valu = String.valueOf(map.get(Model));
                    List<String> values = new ArrayList<>();
                    if (ObjectUtil.isNotEmpty(valu)) {
                        values = Arrays.asList(valu.split(","));
                    }
                    String returncalue = "";
                    if (ObjectUtil.isNotEmpty(multiple) || "checkbox".equals(tagIcon)) {
                        for (int i = 0; i < values.size(); i++) {
                            for (Map mapvalue : mapList) {
                                if (String.valueOf(mapvalue.get(dislinkName)).equals(String.valueOf(values.get(i)))) {
                                    returncalue = returncalue + mapvalue.get(disFieldName) + ",";
                                }
                            }
                        }
                    } else {
                        for (Map mapvalue : mapList) {
                            if (String.valueOf(mapvalue.get(dislinkName)).equals(String.valueOf(map.get(Model)))) {
                                returncalue = String.valueOf(mapvalue.get(disFieldName));
                            }
                        }
                    }
                    if (ObjectUtil.isNotEmpty(returncalue)) {
                        if (returncalue.substring(returncalue.length() - 1).equals(",")) {
                            returncalue = returncalue.substring(0, returncalue.length() - 1);
                        }
                    }
                    if("null".equals(returncalue)){
                        returncalue = "";
                    }
                    map.put(Model, returncalue);
                }
            }
        }
        //编码
        if("coding".equals(tagIcon) && map.get(Model) !=null ){
            String codeData = map.get(Model).toString();
            for (int i = 1; i <= 9; i++) {
                codeData =  codeData.replace("~A%"+i,"");
            }
            map.put(Model,codeData);
        }
        //部门
        if("depart".equals(tagIcon) && "outdata".equals(portal)){
            List<DeptRespDTO> list = realdeptService.selectListAll().getCheckedData();
            String valu = String.valueOf(map.get(Model));
            List<String> values = new ArrayList<>();
            if(ObjectUtil.isNotEmpty(valu)){
                values = Arrays.asList(valu.split(","));
            }
            String returncalue = "";
            if(ObjectUtil.isNotEmpty(multiple)){
                for (int i = 0; i <values.size() ; i++) {
                    for (int  k= 0; k <list.size() ; k++) {
                        if (String.valueOf(list.get(k).getId()).equals(values.get(i))) {
                            returncalue = returncalue + list.get(k).getName() + ",";
                        }
                    }
                }
            }else{
                for (int  k= 0; k <list.size() ; k++) {
                    if (String.valueOf(list.get(k).getId()).equals(String.valueOf(map.get(Model)))) {
                        returncalue = list.get(k).getName();
                    }
                }
            }
            if(ObjectUtil.isNotEmpty(returncalue)){
                if(returncalue.substring(returncalue.length()-1).equals(",")){
                    returncalue = returncalue.substring(0,returncalue.length() - 1);
                }
            }
            if("null".equals(returncalue)){
                returncalue = "";
            }
            map.put(Model,returncalue);
        }
        //用户
        if("user".equals(tagIcon)){
            List<AdminUserRespDTO> list = realadminUserService.selectListAll();
            String valu = String.valueOf(map.get(Model));
            List<String> values = new ArrayList<>();
            if(ObjectUtil.isNotEmpty(valu)){
                values = Arrays.asList(valu.split(","));
            }
            String returncalue = "";
            if(ObjectUtil.isNotEmpty(multiple)){
                for (int i = 0; i <values.size() ; i++) {
                    for (int  k= 0; k <list.size() ; k++) {
                        if (String.valueOf(list.get(k).getId()).equals(values.get(i))) {
                            returncalue = returncalue + list.get(k).getNickname() + "/" + list.get(k).getUsername() + ",";
                        }
                    }
                }
            }else{
                for (int  k= 0; k <list.size() ; k++) {
                    if (String.valueOf(list.get(k).getId()).equals(String.valueOf(map.get(Model)))) {
                        returncalue = list.get(k).getNickname() + "/" + list.get(k).getUsername();
                    }
                }
            }
            if(ObjectUtil.isNotEmpty(returncalue)){
                if(returncalue.substring(returncalue.length()-1).equals(",")){
                    returncalue = returncalue.substring(0,returncalue.length() - 1);
                }
            }
            if(ObjectUtil.isEmpty(returncalue)){
                returncalue = valu;
            }
            if("null".equals(returncalue)){
                returncalue = "";
            }
            map.put(Model,returncalue);
        }
        //岗位
        if("post".equals(tagIcon)){
            List<PostDTO> list = realpostService.selectListAll().getCheckedData();
            String valu = String.valueOf(map.get(Model));
            List<String> values = new ArrayList<>();
            if(ObjectUtil.isNotEmpty(valu)){
                values = Arrays.asList(valu.split(","));
            }
            String returncalue = "";
            if(ObjectUtil.isNotEmpty(multiple)){
                for (int i = 0; i <values.size() ; i++) {
                    for (int  k= 0; k <list.size() ; k++) {
                        if (String.valueOf(list.get(k).getId()).equals(values.get(i))) {
                            returncalue = returncalue + list.get(k).getName() + ",";
                        }
                    }
                }
            }else{
                for (int  k= 0; k <list.size() ; k++) {
                    if (String.valueOf(list.get(k).getId()).equals(String.valueOf(map.get(Model)))) {
                        returncalue = list.get(k).getName();
                    }
                }
            }
            if(ObjectUtil.isNotEmpty(returncalue)){
                if(returncalue.substring(returncalue.length()-1).equals(",")){
                    returncalue = returncalue.substring(0,returncalue.length() - 1);
                }
            }
            if(ObjectUtil.isEmpty(returncalue)){
                returncalue = valu;
            }
            if("null".equals(returncalue)){
                returncalue = "";
            }
            map.put(Model,returncalue);
        }
        //级联
        if("cascader".equals(tagIcon)){
            String valueall = "";
            String model = String.valueOf(map.get(Model));
            if (StringUtils.isNoneBlank(model)) {
                List<String> values  = Arrays.asList(model.split(","));
                JSONArray fields = field.getJSONArray("fields");
                if(ObjectUtil.isNotEmpty(fields) && ObjectUtil.isNotEmpty(values)){
                    for (int i = 0; i <values.size() ; i++) {
                        JSONObject fieldvalue = (JSONObject) fields.get(i);
                        String value = values.get(i);
                        Long tableName = fieldvalue.getLong("tableName");
                        CommonResult json = realrdbapiService.sourceTestList(tableName);
                        Map<Object,Object> mappp = (Map<Object, Object>) json.getData();
                        List<Map<Object,Object>>  mapList = (List<Map<Object, Object>>) mappp.get("rowMaps");
                        JSONArray datas = fieldvalue.getJSONArray("datas");
                        for (int j = 0; j <datas.size() ; j++) {
                            JSONObject data = (JSONObject) datas.get(j);
                            String showName = data.getString("showName");
                            String fieldName = data.getString("fieldName");
                            for (Map mapvalue:mapList) {
                                if(String.valueOf(mapvalue.get(fieldName)).equals(value)){
                                    valueall = valueall + mapvalue.get(showName) + ",";
                                }
                            }
                        }
                    }
                    if(ObjectUtil.isNotEmpty(valueall)){
                        if(valueall.substring(valueall.length()-1).equals(",")){
                            valueall = valueall.substring(0,valueall.length() - 1);
                        }
                    }
                    if("null".equals(valueall)){
                        valueall = "";
                    }
                    map.put(Model,valueall);
                }
            }
        }
        //时间组件
        if("date".equals(tagIcon)) {
            String value = String.valueOf(map.get(Model));
            String type = field.getString("format");
            if(!"null".equals(value)){
                if ("yyyy".equals(type)) {
                    value = value.substring(0,4);
                }
                if ("yyyy-MM-dd".equals(type)) {
                    value = value.substring(0,10);
                }
                if ("yyyy-MM".equals(type)) {
                    value = value.substring(0,7);
                }
                if ("yyyy-MM-dd HH:mm:ss".equals(type)) {
                    value = value.replace("T"," ");
                }
            }
            map.put(Model,value);
        }
        //数字组件
        if("number".equals(tagIcon)) {
            String value = String.valueOf(map.get(Model));
            JSONObject config = field.getJSONObject("__config__");
            String type = config.getString("numberType");
            if(!"null".equals(value)){
                if ("percentage".equals(type)) {
                    BigDecimal b = new BigDecimal(String.valueOf(value));
                    BigDecimal c = new BigDecimal(String.valueOf(100));
                    value = String.valueOf(b.multiply(c).intValue());
                }
            }
            map.put(Model,value);
        }
        if("null".equals(String.valueOf(map.get(Model)))){
            map.put(Model,"");
        }
        if("create_time".equals(Model)){
            map.put(Model,String.valueOf(map.get(Model)).replace("T"," "));
        }
        return map;
    }

    //导出模板获取数据库全部值
    static String modelDataMapping(JSONObject field, String datatype) {
        String req = "";
        //静态数据
        if("static".equals(datatype)){
            JSONArray options = field.getJSONArray("options");
            for (int  k= 0; k <options.size() ; k++) {
                if(k==options.size()-1){
                    req = req + options.getJSONObject(k).getString("label");
                }else{
                    req = req + options.getJSONObject(k).getString("label")+",";
                }
            }
        }
        //数据字典
        if("dictionary".equals(datatype)){
            String dictType = field.getString("dictName");
            List<DictDataDTO> list = realdictDataService.getListByDictType(dictType).getCheckedData();
            for (int  k= 0; k <list.size() ; k++) {
                if(k==list.size()-1){
                    req = req + list.get(k).getLabel();
                }else{
                    req = req + list.get(k).getLabel()+",";
                }
            }
        }
        //数据源
        if("datasource".equals(datatype)){
            Long disTableName = field.getLong("tableName");
            String disFieldName = field.getString("fieldName");
            String dislinkName = field.getString("saveFieldName");
            if(ObjectUtil.isNotEmpty(disTableName) && ObjectUtil.isNotEmpty(disFieldName)){
                //List<Map<String,Object>> sysDistanceDataVoList = realsysCurrencyService.getDistanceData(disTableName,disFieldName,dislinkName);
                CommonResult json = realrdbapiService.sourceTestList(disTableName);
                Map<Object,Object> mappp = (Map<Object, Object>) json.getData();
                List<Map<Object,Object>>  sysDistanceDataVoList = (List<Map<Object, Object>>) mappp.get("rowMaps");
                if(ObjectUtil.isNotEmpty(sysDistanceDataVoList)){
                    for (int k = 0; k <sysDistanceDataVoList.size() ; k++) {
                        if(k==sysDistanceDataVoList.size()-1){
                            req = req + sysDistanceDataVoList.get(k).get(disFieldName);
                        }else{
                            req = req + sysDistanceDataVoList.get(k).get(disFieldName)+",";
                        }
                    }
                }
            }
        }
        return req;
    }


    /**
     *列表类型
     */
    public static Boolean treeList(String json) {
        if(ObjectUtil.isNotEmpty(json)){
            JSONObject personData = JSON.parseObject(json);
            JSONObject rightConfig = personData.getJSONObject("rightConfig");
            String panelType = rightConfig.getString("panelType");
            if(panelType.equals("tree-list")){ return false; }
            return true;
        }
        return false;
    }
}

